#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>
#include <QDebug>

#include "dialog.h"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout;

    graphic = new GraphWidget();
    mainLayout->addWidget(graphic, 1);

    QHBoxLayout *buttonLayout = new QHBoxLayout;

    resetButton = new QPushButton("reset");
    buttonLayout->addWidget(resetButton);
    leftButton = new QPushButton("left");
    buttonLayout->addWidget(leftButton);
    rightButton = new QPushButton("right");
    buttonLayout->addWidget(rightButton);
    zoomInButton = new QPushButton("zoom in");
    buttonLayout->addWidget(zoomInButton);
    zoomOutButton = new QPushButton("zoom out");
    buttonLayout->addWidget(zoomOutButton);

    openButton = new QPushButton("load file");
    buttonLayout->addWidget(openButton);

    mainLayout->addLayout(buttonLayout);

    journal = new QComboBox();
    mainLayout->addWidget(journal);

    QObject::connect(openButton, SIGNAL(clicked()), this, SLOT(openButtonClicked()));
    QObject::connect(resetButton, SIGNAL(clicked()), graphic, SLOT(reset()));
    QObject::connect(leftButton, SIGNAL(clicked()), graphic, SLOT(left()));
    QObject::connect(rightButton, SIGNAL(clicked()), graphic, SLOT(right()));
    QObject::connect(zoomInButton, SIGNAL(clicked()), graphic, SLOT(zoomIn()));
    QObject::connect(zoomOutButton, SIGNAL(clicked()), graphic, SLOT(zoomOut()));

    this->setLayout(mainLayout);

    data = 0;

    resize(640, 480);
}

void Dialog::logEvent(QString str)
{
    journal->addItem(str);
}

void Dialog::loadFile(QString fname)
{
    QFile file(fname);

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        logEvent(tr("Failed to open file\"%1\"").arg(fname));
    }

    if(file.size() < 50) {
        logEvent(tr("File\"%1\" is too small").arg(fname));
        file.close();
        return;
    }

    // quite bad approximation...
    data = new double[file.size()/2];

    QTextStream fileStream(&file);

    int pos = 0;
    double x;
    short y;
    for(;;) {
        fileStream >> x;
        if(fileStream.status() == QTextStream::ReadCorruptData) {
            QMessageBox::warning(this, tr("Warning"), tr("Error reading file at position").arg(fileStream.pos()));
            delete [] data;
            data = 0;
            graphic->repaint();
            return;
        }
        if(fileStream.atEnd()) {
            break;
        }
        data[pos++] = x;
    }

    dataLen = pos;

    qDebug() << dataLen << "were read";

    file.close();
}

void Dialog::openButtonClicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
        tr("Open data file"), "",
        tr("All Files (*);;Text Files (*.txt)"));

    if(!fileName.isNull()) {
        loadFile(fileName);
        graphic->setData(data, dataLen);
    }
}


Dialog::~Dialog()
{

}
